package transformer

import (
	"bytes"
	"feishu-alter/common"
	"feishu-alter/global"
	"feishu-alter/model"
	"feishu-alter/templates"
	"strings"
	"text/template"
	"time"

	"gopkg.in/errgo.v2/errors"
)

func TransformToFeishu(notification model.Notification) (model.FeishuMsg, error) {
	//groupKey := notification.GroupKey
	status := notification.Status
	//annotations := notification.CommonAnnotations
	alerts := notification.Alerts
	header := model.Header{
		Title: &model.Element{
			Tag: "plain_text",
		},
	}
	if status == common.RESOLVED {
		header.Template = "green"
		header.Title.Content = "prometheus  恢复"
	} else if status == common.FIRING {
		header.Template = "red"
		header.Title.Content = "prometheus  告警"
	} else {
		return model.FeishuMsg{}, errors.New("unknown alert status")
	}

	var elements []*model.Element

	cstZone := time.FixedZone("CST", 8*3600)

	for _, alert := range alerts {
		// 更改时区
		if !alert.StartsAt.IsZero() {
			alert.StartsAt = alert.StartsAt.In(cstZone)
		}
		if !alert.EndsAt.IsZero() {
			alert.EndsAt = alert.EndsAt.In(cstZone)

		}

		// 解析告警模板
		temp, err := template.ParseFS(templates.FS, "alert.tpl")
		if err != nil {
			return model.FeishuMsg{}, err
		}

		var buffer bytes.Buffer
		err = temp.Execute(&buffer, alert)
		if err != nil {
			return model.FeishuMsg{}, err
		}

		element := model.Element{
			Tag:     "markdown",
			Content: strings.Trim(buffer.String(), "\r\n"),
		}
		elements = append(elements, &element, &model.Element{Tag: "hr"})
	}

	button := model.Button{
		Tag: "button",
		Text: model.Element{
			Tag:     "plain_text",
			Content: "查看监控",
		},
		Url:  global.Config.GrafanaUrl,
		Type: "primary",
	}

	alertButton := model.Button{
		Tag: "button",
		Text: model.Element{
			Tag:     "plain_text",
			Content: "查看告警",
		},
		Url:  global.Config.PrometheusUrl,
		Type: "primary",
	}

	elements = append(elements,
		&model.Element{Tag: "markdown", Content: "<at id=all>"},
		&model.Element{Tag: "hr"},
		&model.Element{Tag: "action", Actions: []*model.Button{&button, &alertButton}},
	)

	msg := model.FeishuMsg{
		MsgType: "interactive",
		Card: &model.Card{
			Header:   &header,
			Elements: elements,
		},
	}

	return msg, nil
}
